import { defineStore } from 'pinia';

export const useJWTStore = defineStore({
  id: 'jwt',

  state: () => {
    const tokenCookie = document.cookie.split('; ').find(row => row.startsWith('sh1='));
    const roleCookie = document.cookie.split('; ').find(row => row.startsWith('sh2='));

    return {
      token: tokenCookie ? tokenCookie.split('=')[1] : null,
      role: roleCookie ? roleCookie.split('=')[1] : null,
    };
  },

  actions: {
    updateToken(token) {
      this.token = token;
      const expires = new Date();
      expires.setDate(expires.getDate() + 14);
      document.cookie = `sh1=${token}; expires=${expires.toUTCString()}; path=/;`;
    },

    updateRole(role) {
      this.role = role;
      const expires = new Date();
      expires.setDate(expires.getDate() + 14);
      document.cookie = `sh2=${role}; expires=${expires.toUTCString()}; path=/;`;
    },

    clearToken() {
      this.token = null;
      document.cookie = 'sh1=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    },

    clearRole() {
      this.role = null;
      document.cookie = 'sh2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    },
  },

  getters: {
    getToken: state => state.token,
    getRole: state => state.role,
  },
});